<template>
  <div class="custom-page">
    <ul class="list-continer">
      <router-link tag="li" to="/custom/addGroup" class="tablist">
        <div class="add-group scale-1px-hairline--bottom">
          <i class="iconfont icon-kehu_tianjia"></i>
          <span class="name">新增分组</span>
        </div>
      </router-link>
      <li class="tablist" v-for="(item, index) of classData" :key="item.id" @click="showHide(index)">
        <div class="main_list" :class="{'main_list_bottom': index === currentIndex }">
          <van-swipe-cell :right-width="160" :data-index="item.classifyId" :disabled="!!item.disabled">
            <div class="userInfo scale-1px-hairline--bottom">
              <p class="title">
                <span class="iconfont" :class="index === currentIndex ? 'icon-wode-zhedie' : 'icon-wode-zhedie1'"></span>
                <span>{{ item.title }}</span>
              </p>
              <p class="text">共{{ item.clientNum }}人</p>
            </div>
            <div slot="right" class="btn">
              <span class="edit" @click="swipeEdit(item)">编辑</span>
              <span class="delete" @click="swipeDelete(item.classifyId)">删除</span>
            </div>  
          </van-swipe-cell>
          <div class="list-info" v-if='currentIndex === index'>   
            <Tips v-if="listInfo.length && (todayCount || yesterdayCount) " :isTool="false" :title="title" 
            :increase="todayCount" :reduce="yesterdayCount" />
            <van-list
              v-model="loading"
              :loading-text="'正在加载中...'"
              :finished="finished"
              :finished-text="item.clientNum === 0 ? prompt : finished && !listInfo.length ? '' : '没有更多了'"
              @load="onLoad"
            >
            <div v-for="(info,index) in listInfo" :key="info.clientId">
              <my-custom-item
                :info="info" :num="index"
                :last="index === listInfo.length - 1"
                @click="itemClickHandler(info)"
                @delete="itemDelete"
              ></my-custom-item>
              <!-- <NewestDivider v-if="findIndex == index" :title="`新增${item.title}`" /> -->
            </div>
            </van-list>
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>
<script>
import Tips from '@/components/Dynamics/Tips'
import MyCustomItem from '../components/MyCustomItem'
import CustomService from 'SERVICE/customService'
import commonService from 'SERVICE/commonService'
import NewestDivider from '@/components/Dynamics/NewestDivider'
import { mapGetters } from 'vuex'

const classData = [ 
  {clientNum: 0, title: "访问客户", disabled: true },
  {clientNum: 0, title: "意向客户", disabled: true },
  {clientNum: 0, title: "留电客户", disabled: true },
  {clientNum: 0, title: "互动客户", disabled: true }
 ]

export default {
  components: {
    Tips,
    MyCustomItem,
    NewestDivider
  },
  data: () => ({
    currentIndex: '',
    prompt: '该分类暂无客户',
    listInfo: [],
    finished: false,
    loading: false,
    page: 1,
    pageSize: 10,
    scrollTop: 0,
    findIndex: 0, 
    classData: [], //客户分类列表
    classifyId: "", //分类id
    classifyType: 1,
  }),
  computed: {
    ...mapGetters(['userInfo']),
  },
  created () {
    let { type, todayCount, yesterdayCount } = this.$route.query
    if (type) {
      this.todayCount =  +todayCount
      this.yesterdayCount = +yesterdayCount
      this.currentIndex = 0
      this.classifyType = type
    } else {
      this.todayCount = 0
      this.yesterdayCount = 0
      this.classData = classData
    }
    let data = window.sessionStorage.getItem('listInfo')
    if (data) { 
      let item = JSON.parse(data)
      this.page = item.page
      this.listInfo = item.listInfo
      this.loading = item.loading
      this.scrollTop = item.scrollTop
      this.classData = item.classData
      this.finished = item.finished
      this.currentIndex = item.currentIndex,
      this.classifyId = item.classifyId
      this.findIndex = item.findIndex
      this.classifyType = item.classifyType
      window.sessionStorage.removeItem('listInfo')
    } else {
      this.getClasslist();
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$el.querySelector('.list-continer').scrollTop = this.scrollTop
    })
  },
  methods: {
    // onClose(clickPosition, instance, detail) {
    //   console.log(detail)
    //   let classifyId = instance.$el.getAttribute('data-index')
    //   switch (clickPosition) {
    //     case 'left':
    //     case 'cell':
    //     case 'outside':
    //       instance.close();
    //       break;
    //     case 'right':
    //        this.$dialog.confirm({
    //         title: '提示',
    //         message: '确定要删除该分组吗？',
    //         className: 'delete-dialog'
    //       }).then(() => {
    //         return CustomService.updateClassifyStatus({
    //           agentId: this.userInfo.agentId,
    //           classifyId: classifyId,
    //           status: 0
    //         })
    //       }).then(res => {
    //         this.classData.some((item, index) => {
    //           if (item.classifyId === classifyId) {
    //             this.classData.splice(index, 1)
    //             return true
    //           }
    //         })
    //         instance.close()
    //       }).catch(() => {
    //         instance.close()
    //       })
    //       break
    //   }
    // },
    async getClasslist () {
      let { type } = this.$route.query
      let defaultList = await CustomService.getCustomerListTypes()
      defaultList.forEach((item, index) => {
        item.type = index + 1
        item.disabled = true
      });
      let classList = await CustomService.getClassifyList()
      classList = classList.filter(item=>item.isDefault == false)
      this.classData = defaultList.concat(classList)
    },
    swipeEdit(item) {
      let { title, classifyId } = item
      this.$router.push(`/custom/addGroup?classifyId=${classifyId}&groupName=${title}`)
    },
    swipeDelete(classifyId) {
      this.$dialog.confirm({
        title: '提示',
        message: '确定要删除该分组吗？',
        className: 'delete-dialog'
      }).then(() => {
        return CustomService.updateClassifyStatus({
          agentId: this.userInfo.agentId,
          classifyId: classifyId,
          status: 0
        })
      }).then(res => {
        this.classData.some((item, index) => {
          if (item.classifyId === classifyId) {
            this.classData.splice(index, 1)
            return true
          }
        })
      })
    },
    showHide(index) {
      this.classifyId = this.classData[index].classifyId
      this.classifyType = this.classData[index].type
      this.cleanCurrentData();
      this.currentIndex = this.currentIndex === index ? '' : index
      if (this.loading) {
        console.log("正在加载")
      }
    },
    //道管理分类页面
    goClasstify() {  
      this.$router.push({ name:'managerClasstify' })
    },
    //到搜索页面
    goSerch () {
      this.$router.push({ name:"serch" })
    },
    cleanCurrentData() {
      this.finished = false
      this.page = 1
      this.listInfo = []
    },
    //获取客户分类列表
    async onLoad() {
      let obj = { current: this.page, size: this.pageSize, type: this.classifyType }
      if (this.classifyId) obj.classifyId = this.classifyId
      const result = await CustomService.getCustomerList(obj)
      // 防止上一次分组的加载没有完成，对数据进行修行
      // 只对当前的分组加载进行
      // if ((!obj.classifyId && this.classifyType === obj.type) || (!obj.type && this.classifyId === obj.classifyId) ){
        if (result.pages === 1) {
          this.listInfo = result.records
        } else {
          this.listInfo = this.listInfo.concat(result.records)
        }
        this.findIndex = this.listInfo.findIndex(item => !item.ifToday) - 1
        this.loading = false
        if (result.pages <= this.page) {
          this.finished = true
        } else { 
          this.finished = false
          this.page++
        }
      // }
      
    },
    itemClickHandler(item) {
      let data = {
        page: this.page,
        listInfo: this.listInfo,
        loading: this.loading,
        scrollTop: this.$el.querySelector('.list-continer').scrollTop,
        currentIndex: this.currentIndex,
        classifyId : this.classifyId,
        classData: this.classData,
        finished : this.finished,
        findIndex: this.findIndex,
        classifyType: this.classifyType
      }
      window.sessionStorage.setItem('listInfo',JSON.stringify(data))
      let query = ""
      if (item.clientStrangerFlag !== 2) {
        query = { thread: 'thread' }
      } else {
        query = { activityTrack: 'activityTrack' }
      }
      this.$router.push( { path: `/custom/${item.clientId}`, query })
    },
    // 删除客户
    async itemDelete (index) {
      try {
        let item = this.listInfo[index]
        let result = await CustomService.deleteCustomer({clientId: item.clientId, clientDelFlag: 2})
        this.classData.forEach((item, index) => {
          if (index === this.currentIndex) {
            item.clientNum -=1
          }
        })
        this.listInfo.splice(index, 1)
        this.$toast('删除成功！')
        this.getClasslist()
      } catch (error) {
        
      }
      
    },
    goBack () {
      // this.$router.replace({path: '/dynamics'});
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less" scoped>
.scale-1px-hairline--bottom::after{
  background:#E4E6F0;
}
/deep/ .tips-container .isBottom {
  margin-bottom: 0;
}

.custom-page {
  background: #F7F9FA;
  position: relative;
  .serchHeader {
    width: 100%; 
    background: #fff;
    padding: 10px 16px; 
    overflow: hidden;
    .serch_input { 
      background: #F2F6F7;
      border-radius: 4px;
      height: 36px;
      width: 100%;
      line-height: 36px;
      display: flex;
      align-items: center;
      i {
        color: #969EA8;
        margin: 0 8px 0 12px;
      }
      .serchText {
        font-size:14px;
        color:#969EA8;
      }
    }
  }
  .list-continer {
    width:100%;
    position: relative;
    height: 100%;
    overflow: hidden;
    overflow-y: scroll;
  }
  .tablist {
    display: flex;
    min-height: 56px;
    align-items: center;
    list-style: none;
    background: #fff;
    overflow: hidden;
    .add-group {
      margin: 0 16px;
      line-height: 56px;
      width: 100%;
      font-size: 16px;
      color: #13284D;
      i {
        color: #5EAE3E;
        padding-right: 4px;
      }
    }
    .main_list {
      flex: 1;
      .userInfo {
        display: flex;
        height: 56px;
        // margin-bottom: 1px;
        align-items: center;
        line-height: 56px;
        // overflow: hidden;
        margin: 0 16px;
      }
      .btn{ 
        display: flex;
        height: 100%;
        width: 160px;
        color: #fff;
        font-size: 16px;
        align-items: center;
        justify-content: center;
        span {
          flex: 1;
          line-height: 56px;
          text-align: center;
        }
        .delete {        
          background-color: #EA4D2E;
        }
        .edit {
          background-color: green;
        }
      }
      // /deep/ .van-swipe-cell {
      //   padding-left: 16px;
      // }
      .rightImg {
        width: 12px;
        height: 12px;
      }
      .title {
        color: #13284D;
        font-size: 16px; 
        font-family:PingFangSC-Medium;
        font-weight:500; 
        flex: 1;
        .iconfont {
          color: #9CA5B5;
          margin-right: 6px;
        }
      }
      .text {
        flex-basis: 100px;
        color: #9BA4B4; 
        font-size:12px;
        font-weight:400; 
        text-align: right;
        // margin-right: 16px;
      }
    }
  }
  .delCoustomerGuide{
    position: fixed;
    width: 100%;
    height: 100vh;
    top: 0;
    bottom: 0;
    background-color: #4c4c4c;
    z-index: 999;
    img {
      width: 100%;
      height: 100vh;
    }
    .btn { 
      width: 95px;
      height: 32px;
      color: #FFFFFF;
      font-size: 17px;
      border-radius:16px; 
      background:rgba(0,0,0,0);
      border:1px solid rgba(255,255,255);
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      left: 0;
    }
  }
}
</style>
